class IncidentsController < ApplicationController
  def index
    @lookup = session[:incident_lookup] || ""
    
    @incidents = Incident.for_index.by_id
    @incidents = @incidents.where(Incident.search_condition(@lookup)) unless @lookup.blank?
    @incidents = @incidents.paginate(:page => params[:page])
  end
  
  def lookup
    session[:incident_lookup] = params[:lookup].blank? ? nil : params[:lookup]
    redirect_to(incidents_path)
  end
  
  def show
    @incidents = [Incident.find(params[:id])]
    render(:action => :index)
  end

  def edit
    @incident = Incident.find(params[:id])
  end
  
  def create
    begin
      i = Incident.create(params[:incident])
      i.add_report(Report.find(params[:report_id])) if params[:report_id]
      flash[:success] = "Incident created successfully."
    rescue
      flash[:error] = $!.to_s
    end
    redirect_to(reports_path)
  end
  
  def update
    @incident = Incident.find(params[:id])
    begin
      ip = params[:incident]
      @incident.update_attributes(ip)
      @incident.save
    rescue
      flash[:error] = $!.to_s
      raise $!
    end
    redirect_to(incidents_path)
  end
  
  def choose
    i = Incident.find(params[:id])
    if i
      i.add_report(Report.find(params[:report_id]))
      flash[:success] = "Incident chosen successfully."
    else 
      flash[:error] = "Coudn't find incident"
    end
    redirect_to(reports_path)
  end

  def picker
    @incidents = Incident.by_id.paginate(:page => params[:page], :per_page => 15)
    @new_incident = Incident.new
    @report_id = params[:report_id]
    render(:layout => nil)
  end
  
  def destroy
    begin
      incident = Incident.find(params[:id])
      incident.destroy
    rescue
      flash[:error] = $!.to_s
    end
    redirect_to(incidents_path)
  end
end
